package com.faxsun.common.currency.domain;

import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.List;

import javax.annotation.Resource;

import org.broadleafcommerce.common.BroadleafEnumerationType;
import org.broadleafcommerce.common.currency.dao.BroadleafCurrencyDao;
import org.broadleafcommerce.common.currency.domain.BroadleafCurrency;
import org.springframework.stereotype.Component;

/**
 * 汇率枚举类型<br/>
 * 从数据库中读取汇率
 * 
 * @author zhaoteng.song@faxsun.com
 *
 */
@Component
public class FSCurrencyEnum implements BroadleafEnumerationType, Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1881907326198797290L;

	private static final LinkedHashMap<String, FSCurrencyEnum> CURRENCIES = new LinkedHashMap<String, FSCurrencyEnum>();

	public static FSCurrencyEnum getInstance(final String type) {
		return CURRENCIES.get(type);
	}

	/**
	 * 根据汇率code解析为对应的实体
	 * @param type
	 * @return
	 */
	public static BroadleafCurrency parse(String type) {
		FSCurrencyEnum bc = CURRENCIES.get(type);
		if (bc != null) {
			return bc.broadleafCurrency;
		}
		return null;
	}

	@Resource(name = "blCurrencyDao")
	protected BroadleafCurrencyDao currencyDao;

	public void init() {
		List<BroadleafCurrency> allCurrencies = currencyDao.getAllCurrencies();
		for (BroadleafCurrency currency : allCurrencies) {
			FSCurrencyEnum c = new FSCurrencyEnum();
			c.code = currency.getCurrencyCode();
			c.friendlyName = currency.getFriendlyName();
			c.broadleafCurrency = currency;
			CURRENCIES.put(c.code, c);
		}
	}

	protected String code;
	protected String friendlyName;
	protected BroadleafCurrency broadleafCurrency;

	@Override
	public String getType() {
		return this.code;
	}

	@Override
	public String getFriendlyType() {
		return this.friendlyName;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((code == null) ? 0 : code.hashCode());
		result = prime * result
				+ ((friendlyName == null) ? 0 : friendlyName.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		FSCurrencyEnum other = (FSCurrencyEnum) obj;
		if (code == null) {
			if (other.code != null)
				return false;
		} else if (!code.equals(other.code))
			return false;
		if (friendlyName == null) {
			if (other.friendlyName != null)
				return false;
		} else if (!friendlyName.equals(other.friendlyName))
			return false;
		return true;
	}

	public void setCurrencyDao(BroadleafCurrencyDao currencyDao) {
		this.currencyDao = currencyDao;
	}

	public BroadleafCurrency getBroadleafCurrency() {
		return broadleafCurrency;
	}

	@Override
	public String toString() {
		return friendlyName;
	}

}
